package com.rc.saas.tenant.controller.tenant;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.common.base.HttpConstant;
import com.rc.saas.tenant.common.constant.ShiroConstants;
import com.rc.saas.tenant.common.sms.AliyunSmsUtil;
import com.rc.saas.tenant.common.sms.AliyunSmsTemplateEnum;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.common.component.UidGenerator;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.service.sms.TenantSmsService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.service.tenant.TenantUserService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * 修改密码
 * Created by sven on 2019/11/21
 */
@Controller
@RequestMapping("/tenant/user")
public class TenantUserModifyEmailController extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(TenantUserModifyEmailController.class);

    private String prefix = "/templates/tenant/user";

    @Autowired
    private UidGenerator uidGenerator;

    @Autowired
    private TenantUserService tenantUserService;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private TenantSmsService tenantSmsService;

    /**
     * 打开修改邮箱页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/modifyEmail", method = RequestMethod.GET)
    public String modifyEmail(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();

        model.addAttribute("user", user);
        return prefix + "/modifyEmail";
    }

    /**
     * 获取手机短信验证码
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/genModifyEmailAuthCode", method = RequestMethod.POST)
    @ResponseBody
    public TResponse genModifyEmailAuthCode(HttpSession session) {
        TenantUser user = ShiroUtils.getSessionUser();
        TenantUser findUser = tenantUserService.selectByPrimaryKey(user.getTenantUserId());

        if (StringUtils.isBlank(findUser.getMobile()) || !findUser.getMobile().matches(HttpConstant.MOBILE_REGEX)) {
            return TResponse.FAIL("手机号格式不正确");
        }
        logger.info("获取手机短信验证码:{},:{}", findUser.getLoginName(), findUser.getMobile());

        //验证码
        String smscode = uidGenerator.genSmsAuthCode();
        Tenant tenant = tenantService.selectByTenantCode(findUser.getTenantCode());
        SendSmsResponse sendResult = AliyunSmsUtil.sendSms(findUser.getMobile(), smscode, AliyunSmsTemplateEnum.CERTIFY, tenant.getSmsSign());

        if (sendResult == null) {
            logger.error("短信系统异常");
            return TResponse.FAIL("短信系统异常");
        }

        if ("OK".equals(sendResult.getCode())) {
            // 更新sms表
            tenantSmsService.updateTenantSmsByTenantCode(tenant.getPhone(), findUser.getTenantCode(), findUser.getTenantUserId(), "0", "tenant,getModifyEmailAuthCode:重置密码,获取验证码:" + findUser.getMobile(), "重置密码,获取验证码");
        }else {
            logger.error("短信系统异常:" + sendResult.getMessage());
        }

        //将登录验证码保存到会话中
        String sessionAttr = ShiroConstants.SESSION_TENANT_MODIFYEMAIL_KEY + findUser.getMobile();
        String sessionAuthCode = smscode + System.currentTimeMillis();
        session.setAttribute(sessionAttr, sessionAuthCode);

        logger.info("获取手机短信验证码 mobile:{},sessionAttr:{},sessionAuthCode:{}", findUser.getMobile(), sessionAttr, sessionAuthCode);

        return TResponse.SUCCESS("验证码已发送");
    }

    /**
     * 保存新邮箱
     *
     * @param session
     * @param password
     * @param email
     * @param authCode
     * @return
     */
    @RequestMapping(value = "/saveNewEmail", method = RequestMethod.POST)
    @ResponseBody()
    public TResponse saveNewEmail(HttpSession session, String password, String email, String authCode) {
        logger.info("controller.saveNewEmail request,:{},:{},:{}", password, email, authCode);

        TenantUser user = ShiroUtils.getSessionUser();
        TenantUser findUser = tenantUserService.selectByPrimaryKey(user.getTenantUserId());

        String sessionAttr = ShiroConstants.SESSION_TENANT_MODIFYEMAIL_KEY + findUser.getMobile();
        String sessionAuthCode = (String) session.getAttribute(sessionAttr);
        if (StringUtils.isBlank(sessionAuthCode)) {
            return TResponse.FAIL("未申请验证码");
        }

        if (!authCode.equals(sessionAuthCode.substring(0, 6))) {
            session.removeAttribute(sessionAttr);
            return TResponse.FAIL("验证码错误");
        }

        if (StringUtils.isBlank(email)) {
            session.removeAttribute(sessionAttr);
            return TResponse.FAIL("无效的电子邮箱");
        }

        try {
            tenantUserService.updatedUserAndTenantEmail(findUser, email);

            //删除验证码
            session.removeAttribute(sessionAttr);
        } catch (Exception e) {
            session.removeAttribute(sessionAttr);
            return TResponse.FAIL("操作失败");
        }

        return TResponse.SUCCESS();
    }
}
